from __future__ import generators
import os
from pyglet.gl import *
from pyglet import image
from pyglet import font
from primitives import Polygon
import math

def round_up( number ):
    """
    Returns a number that is rounded up to the next whole number.
    >>> round_up( 2.2 )
    3
    >>> round_up( 4 )
    4
    """
    i_number = int(number)
    if i_number == number:
        return i_number
    else:
        return i_number + 1

def between( n, bottom, top ):
    """
    Returns True if n is >= bottom and <= top
    >>> between( 5, 1, 10 )
    True
    """
    return n >= bottom and n <= top

def distance( start, end ):
    """
    Returns the distance between two points as a float.
    >>> distance( (1,1), (4,4) )
    4.2426406871192848
    """
    return math.sqrt( distance_squared(start, end) )

def distance_squared( start, end ):
    """
    Same as distance only it returns the distance squared. Saves computation
    time of using math.sqrt.
    """
    return ((end[0] - start[0]) ** 2) + ((end[1] - start[1]) ** 2)

def cycle(maximum = 2):
    """
    A simple generator that cycles through a list of integers
    """
    cur = 0
    yield cur
    while 1:
        if cur == maximum:
            cur = 0
        else:
            cur += 1
        yield cur

def coord_to_tile( *args ):
    try:
        x,y = args[0]
    except:
        x,y = args[:2]
    """
    figure out the tile coord based upon x and y
    FUTURE: return the tile object
    """
    return (x//32,y//32)

def constrain( val, minimum, maximum ):
    """
    Returns a value constrained to specified minimum and maxium.
    """
    return max(min(val,maximum),minimum)

def flatten(l, ltypes=(list, tuple)):
  """
  Flattens a list really fast.
  """
  i = 0
  while i < len(l):
    while isinstance(l[i], ltypes):
      if not l[i]:
        l.pop(i)
        if not len(l):
          break
      else:
        l[i:i+1] = list(l[i])
    i += 1
  return l
